package com.baitiaojun.auth.service.impl;

import com.baitiaojun.api.domain.auth.AuthRoleElementOperation;
import com.baitiaojun.api.domain.auth.AuthRoleMenu;
import com.baitiaojun.api.domain.auth.UserAuthorities;
import com.baitiaojun.api.domain.auth.UserRole;
import com.baitiaojun.api.exception.ConditionException;
import com.baitiaojun.api.util.ConstantUtil;
import com.baitiaojun.api.util.SnowFlakeUtil;
import com.baitiaojun.auth.service.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @类名 UserAuthoritiesServiceImpl
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2022/12/7 21:04
 * @版本 1.0
 */
@Service
public class UserAuthoritiesServiceImpl implements UserAuthoritiesService {

    @Resource
    private AuthRoleElementOperationService authRoleElementOperationService;

    @Resource
    private AuthRoleMenuService authRoleMenuService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private AuthRoleService authRoleService;

    @Override
    public UserAuthorities getUserAuthorities(Long userId) {
        Long roleId = userRoleService.getRoleIdByUserId(userId);
        List<AuthRoleElementOperation> authRoleElementOperations
                = authRoleElementOperationService.getRoleElementOperations(roleId);
        List<AuthRoleMenu> authRoleMenus
                = authRoleMenuService.getAuthRoleMenus(roleId);
        return UserAuthorities.builder()
                .authRoleElementOperations(authRoleElementOperations)
                .authRoleMenus(authRoleMenus)
                .build();
    }

    @Override
    public void addDefaultRole(Long userId) throws ConditionException {
        Long roleId = authRoleService.getAuthRoleIdByCode(ConstantUtil.ROLE_LV0);
        userRoleService.addUserRole(UserRole.builder()
                        .id(SnowFlakeUtil.getNextId())
                        .userid(userId)
                        .roleid(roleId)
                        .createtime(new Date()).build());
    }
}
